﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using CreditAgricole.Framework;

namespace CreditAgricole.CommonElements.Event_Receivers.TaskListEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class TaskListEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// An item is being deleted.
        /// </summary>
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            //Built in call to the initial definition
            base.ItemDeleting(properties);

            SPListItem myItem;
            try
            {
                // Get reference to the current item being deleted
                myItem = properties.ListItem;
                // Read the status field of the item being deleted
                String taskStatus = myItem["Status"].ToString();

                // Is the task status is Completed it's not an active task anymore
                // Otherwise we cancel the deletion
                if (taskStatus != "Completed")
                {
                    // This is the message that we'd like to show to the user
                    // if he/she tries to delete an active task
                    properties.ErrorMessage = "This task is still in progress and cannot be deleted";
                    // This line actually cancels the delete
                    properties.Cancel = true;
                }
            }
            catch(Exception ex)
            {
                if (!string.IsNullOrEmpty(ex.Message)) CALoggingHelper.AddErrorEntry(string.Format("TaskItemDeleting - Error :\n\n{0}", ex.Message));
            }
        }
    }
}
